package ru.aslanov.schedule.server.services;

import ru.aslanov.schedule.model.DataItem;
import ru.aslanov.schedule.model.InputLang;
import ru.aslanov.schedule.model.Operation;
import ru.aslanov.schedule.model.Schedule;
import ru.aslanov.schedule.server.AccessDeniedException;
import ru.aslanov.schedule.server.AccessManager;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Sergey Aslanov
 *         Created: Oct 13, 2010 4:47:19 PM
 */
public class InputLangService extends ScheduleChildService<InputLang> {

    public InputLangService() {
        super("name");
    }

    @Override
    protected Class<InputLang> getEntityClass() {
        return InputLang.class;
    }


    @Override
    protected void fillDataItem(DataItem dataItem, InputLang object, HttpServletRequest request, PersistenceManager pm) throws Exception {
        final Schedule schedule = getParent(pm, request);

        super.fillDataItem(dataItem, object, request, pm);
        setAttr(dataItem, "schedule", object.getSchedule());
        setAttr(dataItem, "id", object.getId());
        setAttr(dataItem, "name", object.getName());
        setAttr(dataItem, "default", object.getId().equals(schedule.getDefaultInputLanguage()));
    }

    @Override
    protected boolean checkPermission(InputLang existingEntity, HttpServletRequest request, PersistenceManager pm, Operation operation) throws AccessDeniedException {
        String scheduleKey = existingEntity != null ? existingEntity.getSchedule().getEncodedKey() : getParentKey(request);

        final AccessManager accessManager = AccessManager.getInstance();
        return operation == Operation.VIEW ? accessManager.hasAccessToSchedule(scheduleKey, operation) : accessManager.isScheduleAdmin(scheduleKey);

    }

    @Override
    protected void makeObjectPersistent(PersistenceManager pm, InputLang object, HttpServletRequest request) {
        final Schedule schedule = getParent(pm, request);
        final List<InputLang> inputLangList = schedule.getInputLangs();
        if (inputLangList.size() == 0) {
            schedule.setDefaultInputLanguage(object.getId());
        }
        inputLangList.add(object);
    }
}
